package com.acme.bankapp.service.bank;

import java.util.Arrays;
import java.util.Date;

import com.acme.bankapp.domain.bank.client.Client;
import com.acme.bankapp.domain.bank.client.ClientRegistrationListener;
import com.acme.bankapp.service.bank.exception.ClientExistsException;

@SuppressWarnings("serial")
public class Bank implements java.io.Serializable {
	public class EmailNotificationListener implements ClientRegistrationListener {
		@Override
		public void onClientAdded(Client c) {
			System.out.println("Notification email for client " + c + " to be sent");
		}
	}
	
	public static class PrintClientListener implements ClientRegistrationListener {
		@Override
		public void onClientAdded(Client c) {
			System.out.println(c);
		}
	}
	
	private int countClients = 0;
	
	public int getCountClients() {
		return countClients;
	}
	
	public void addClient(Client client) throws ArrayIndexOutOfBoundsException, ClientExistsException {
		if (countClients == MAX_CLIENTS)
			throw new ArrayIndexOutOfBoundsException("The bank has already contains the maximum number of clients");
		for (int i = 0; i < countClients; i++) {
			if (clients[i].getClientSalution().equals(client.getClientSalution()))
				throw new ClientExistsException();
		}
		clients[countClients] = client;
		countClients++;
		for (int i = 0; i < countListeners; i++) {
			listeners[i].onClientAdded(client);
		}
	}
	
	private int countListeners = 0;
	
	public int getCountListeners() {
		return countListeners;
	}
	
	public void addListener(ClientRegistrationListener listener) throws ArrayIndexOutOfBoundsException {
		if (countListeners == MAX_LISTENER) {
			throw new ArrayIndexOutOfBoundsException("The bank has alreade contains the maximum number of clients");
		}
		listeners[countListeners] = listener;
		countListeners++;
	}
	
	public static final int MAX_LISTENER = 3;
	
	private ClientRegistrationListener[] listeners;
	
	public static final int MAX_CLIENTS = 10;
	
	private Client[] clients;
	
	public Bank(ClientRegistrationListener[] listeners) throws ArrayIndexOutOfBoundsException {
		clients = new Client[MAX_CLIENTS];
		this.listeners = new ClientRegistrationListener[MAX_LISTENER];
		
		class DebugListener implements ClientRegistrationListener {
			@Override
			public void onClientAdded(Client c) {				
				System.out.println("Client: " + c + "; time: " + new Date());
			}
		}
		addListener(new DebugListener());
		for (int i = 0 ; i < listeners.length; i++) {
			addListener(listeners[i]);
		}
	}
	
	public Client[] getClients() {
		return Arrays.copyOf(clients,  countClients);
	}
}